package com.ocom.mqsubsidy.business.grantsubsidy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.SubsidyDto;
import com.ocom.common.entity.payconfig.EntitySubsidyData;
import com.ocom.common.vo.GrantSubsidyVo;
import com.ocom.mqsubsidy.config.GrantSubsidyConfig;
import com.ocom.mqsubsidy.config.SubsidyConfig;
import com.ocom.mqsubsidy.feign.PayConfigClientService;
import com.ocom.mqsubsidy.feign.PayHandleClientService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;


@Component
public class GrantSubsidyConsumerMqListener {

	private Logger logger = LoggerFactory.getLogger(GrantSubsidyConsumerMqListener.class);



	@Autowired
	private PayHandleClientService payHandleClientService;



	/**
	 * 把该监听命名为A监听
	 * 监听队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues = GrantSubsidyConfig.GRANT_SUBSIDY_QUEUE)
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		logger.info("grantSubsidy 消费中");
		logger.info("message【{}】",message);
		String humanMessage = new String(message.getBody(), StandardCharsets.UTF_8);
		//TODO 数据库操作样例
		logger.info("grantSubsidy:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());

		SubsidyDto subsidyDto = JSON.parseObject(humanMessage, SubsidyDto.class);

		try {
			payHandleClientService.ccbzhshGrantSubsidy(subsidyDto);
		} catch (Exception e) {
			logger.info("grantSubsidy-出现异常队列消息开始进入死信队列{{}}",e);
		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
		logger.info("grantSubsidy-end:【{}】",humanMessage);
		logger.info("System.currentTimeMillis()【{}】",System.currentTimeMillis());
	}

	/**
	 * 把该监听命名为B监听
	 * 监听死信队列  远程服务支付接口发送消息  该队列会接受
	 * [message, headers, channel]
	 * @return {@link }
	 * @throws
	 */
	@RabbitListener(queues =  SubsidyConfig.SUBSIDY_DIE_QUEUE)
	public void processForDie(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		//死信队列放弃
		channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		logger.info("发放补贴-死信队列放弃 ， 【{}】",message);
	}


}
